﻿using JNPF.Basics.Models;
using JNPF.Basics.Models.WorkFlow.Model;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 流程节点
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-06-14 
    /// </summary>
    public class FlowTaskNodeBll
    {
        private FlowTaskNodeIService service = new FlowTaskNodeService();

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="taskId">任务主键</param>
        /// <returns></returns>
        public async Task<List<FlowTaskNodeEntity>> GetList(string taskId)
        {
            try
            {
                return await service.GetList(taskId);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<FlowTaskNodeEntity> GetInfo(string id)
        {
            try
            {
                return await service.GetInfo(id);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 删除（根据实例Id）
        /// </summary>
        /// <param name="taskId">任务主键</param>
        /// <returns></returns>
        public async Task DeleteByTaskId(string taskId)
        {
            try
            {
                await service.DeleteByTaskId(taskId);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entitys">实体对象</param>
        /// <returns></returns>
        public async Task Create(List<FlowTaskNodeEntity> entitys)
        {
            try
            {

                List<FlowTaskNodeEntity> entityList = new List<FlowTaskNodeEntity>();
                List<FlowTaskNodeEntity> startNodes = entitys.FindAll(x => x.NodeType.Equals("start"));
                if (startNodes.Count > 0)
                {
                    List<FlowTaskNodeEntity> _treeList = new List<FlowTaskNodeEntity>();
                    var startNode = startNodes[0].NodeCode;
                    List<string> rule = new List<string>();
                    long count = 0;
                    ToFilterNodeList(entitys, startNode, _treeList, 0, rule);
                    if (rule.Count > 0)
                    {
                        var title = string.Join(",", rule);
                        throw new Exception(title + " 流程引擎节点规则不符");
                    }
                    //验证流程规则
                    string nodeNext = "end";
                    for (int i = 0; i < _treeList.Count; i++)
                    {
                        var entity = _treeList[i];
                        entity.State = "0";
                        if (entity.NodeNext.IsEmpty())
                        {
                            entity.NodeNext = nodeNext;
                            if (entity.SortCode > count)
                            {
                                count = long.Parse(entity.SortCode.ToString());
                            }
                        }
                        entityList.Add(entity);
                    }
                    entityList.Add(new FlowTaskNodeEntity()
                    {
                        Id = CommonHelper.Guid,
                        NodeCode = nodeNext,
                        NodeName = "结束",
                        Completion = 0,
                        CreatorTime = DateTime.Now,
                        SortCode = count + 1,
                        TaskId = _treeList[0].TaskId,
                        NodePropertyJson = startNodes[0].NodePropertyJson,
                        NodeType = "endround",
                        State = "0"
                    });
                    await service.Create(entityList);
                }
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(FlowTaskNodeEntity entity)
        {
            try
            {
                return await service.Update(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        #region private Method
        /// <summary>
        /// 采用递归过滤节点数据：开始节点 > xxx节点 > xxx节点 > xxx节点【按顺序写入到数据库】注意：必须是开始节点开始计算下一个节点
        /// </summary>
        /// <param name="data"></param>
        /// <param name="nodeCode"></param>
        /// <param name="_treeList"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        private void ToFilterNodeList(List<FlowTaskNodeEntity> data, string nodeCode, List<FlowTaskNodeEntity> _treeList, int index, List<string> rule)
        {
            index++;
            var thisEntity = data.Find(t => t.NodeCode == nodeCode);
            if (!thisEntity.IsEmpty())
            {
                thisEntity.SortCode = index;
                if (!string.IsNullOrEmpty(thisEntity.NodeNext))
                {
                    if (!"start".Equals(thisEntity.NodeType))
                    {
                        ruleList(thisEntity, data, rule);
                    }
                    ToFilterNodeList(data, thisEntity.NodeNext, _treeList, index, rule);
                }
                _treeList.Add(thisEntity);
            }

        }

        private void ruleList(FlowTaskNodeEntity thisEntity, List<FlowTaskNodeEntity> data, List<String> rule)
        {
            FlowTaskNodeEntity nextEntity = data.Find(x => x.NodeCode.Equals(thisEntity.NodeNext));
            if (nextEntity != null)
            {
                ChildNodeModelList thisModel = thisEntity.NodePropertyJson.ToObject<ChildNodeModelList>();
                var thisType = thisModel.assigneeType;
                ChildNodeModelList nextModel = nextEntity.NodePropertyJson.ToObject<ChildNodeModelList>();
                var nextType = nextModel.assigneeType;
                switch (thisType)
                {
                    case 1://主管判断下一级是否主管
                        if (nextType.Equals(thisType))
                        {
                            rule.Add(nextEntity.NodeName);
                        }
                        break;
                    case 7://加签判断下一级是否加签
                        if (nextType.Equals(thisType))
                        {
                            rule.Add(nextEntity.NodeName);
                        }
                        break;
                    case 8://会签判断下一级是否加签
                        if (nextType.Equals(FlowTaskOperatorEnum.FreeApprover))
                        {
                            rule.Add(nextEntity.NodeName);
                        }
                        break;
                    case 3://本人判断下一级是否本人
                        if (nextType.Equals(thisType))
                        {
                            rule.Add(nextEntity.NodeName);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        #endregion
    }
}